package com.jf3q.security.controller;

import com.jf3q.common.vo.ResultVo;
import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.common.vo.AclUserVo;
import com.jf3q.security.entity.EduAclUser;
import com.jf3q.security.service.EduAclPermissionService;
import com.jf3q.security.service.impl.EduAclUserServiceImpl;
import com.jf3q.security.vo.AclUserInfoVo;
import com.jf3q.security.vo.MenuVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:xiaojie
 * @create: 2023-05-07 23:30
 * @Description:
 */
@RestController
@RequestMapping("/acl/user")
@Tag(name = "后台用户controller")
public class AclUserController {
    @Resource
    EduAclUserServiceImpl eduAclUserService;
    @Resource
    EduAclPermissionService permissionService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/login")
    @Operation(summary = "后台用户登录")
    public ResultVo login(@RequestBody AclUserVo userVo, HttpServletRequest request){
        Map<String,String> resultMap = new HashMap<>();
        String username = userVo.getUsername();
        String password = userVo.getPassword();

        UserDetails user = eduAclUserService.loadUserByUsername(username);

        if (null==user||!passwordEncoder.matches(password,user.getPassword())){
            return ResultVo.error("用户名或密码不正确");
        }
        if (!user.isEnabled()){
            return ResultVo.error("账号被禁用，请联系管理员！");
        }

        /**
         * 用户认证通过后，为了避免用户的每次操作都进行认证可将用户的信息保存在会话中。
         * spring security 提供会话管理，
         * 认证通过后将身份信息放入SecurityContextHolder上下文
         */
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password,user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token);

        //生成token
        String tokenStr = jwtTokenUtil.getToken(username);

        resultMap.put("token",tokenStr);
        return ResultVo.success("登录成功",resultMap);
    }
    @Operation(summary = "获取登陆者的基本信息")
    @GetMapping("/info")
    public ResultVo info(String token){
        EduAclUser aclUser = (EduAclUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //根据用户ID查他的菜单
        AclUserInfoVo vo = new AclUserInfoVo();
        BeanUtils.copyProperties(aclUser,vo);

        List<MenuVo> menuVos = permissionService.selectMenuByUserId(aclUser.getId());
//        List<JSONObject> permissionList = permissionService.selectPermissionByUserId(aclUser.getId());
        vo.setMenus(menuVos);

        return ResultVo.success("获取登陆者信息成功",vo);
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public ResultVo logout(HttpServletRequest request, HttpServletResponse response){
        //将项目中的用户信息清空
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication !=null){
            new SecurityContextLogoutHandler().logout(request,response,authentication);
        }
        response.setContentType("application/json;chartset=utf-8");
        //请求头里的jwt令牌置空
        response.setHeader("Authorization","");
        return ResultVo.success("注销成功",null);
    }


}
